<?php


namespace app\common;

use think\facade\Validate;
use think\file\UploadedFile;
use \think\response\Json;
use \Exception;
use \think\facade\Filesystem;
/**图片操作
 * Class Image
 * @package app\common
 */
class Image
{
    /**单图片上传
     * @param UploadedFile $file
     * @param $desc
     * @param array $cof size允许上传文件大小 mine 允许上传类型
     * @return bool|string|Json
     */
    public static function uploadSingle(UploadedFile $file, $desc = '' ,$cof = ['size' => 1024 * 400, 'mine' => ['image/jpeg', 'image/jpg', 'image/png']])
    {
        try {
            if (!$file) return jsonFail('获取图片失败');
            if (!isset($cof['size'])) return jsonFail('参数配置错误');
            if (!isset($cof['mine'])) return jsonFail('参数配置错误');
            $input['size'] = $file->getSize();
            $input['mine'] = $file->getMime();
            // 参数校验
            $validate = Validate::rule([
                'size' => function($value) use($cof) {
                    if ($value === null) {
                        return '缺少参数';
                    } elseif ($value > $cof['size']) {
                        return '最大允许上传' . ($cof['size'] / 1024) . 'kb图片';
                    } else{
                        return true;
                    }
                },
                'mine' => function($value) use ($cof){
                    if ($value === null) {
                        return '缺少参数';
                    } elseif (!in_array($value, $cof['mine'])) {
                        return '只允许上传' .  implode('|', $cof['mine']) .'图片';
                    } else{
                        return true;
                    }
                }
            ]);

            if (!$validate->check($input)) {
                return jsonFail($validate->getError());
            }
            $savename = Filesystem::disk('public')->putFile( $desc, $file);
            if ($savename) return $savename;
            return jsonFail('上传失败');
        } catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /** 删除图片
     * @param $path
     * @return bool
     */
    public static function delete($path)
    {
        if (is_string($path)) {
            return @unlink($path);
        } else if (is_array($path)) {
            foreach ($path as $v) {
                @unlink($v);
            }
            return true;
        } else {
            return false;
        }
    }
}